package com.eightbitcloud.pagingscroller;

import java.io.IOException;
import java.net.MalformedURLException;
import java.util.LinkedList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import com.daydr3am.thenation.RootScroll;

import android.content.Context;
import android.os.AsyncTask;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;

public class Pager extends HorizontalScrollView {
    protected LinearLayout contents;
    public String url;
    private LinkedList<OnPageChangeListener> listeners;
    protected Context con;

	protected int newCheck = 100;
	protected NodeList list;
//	public int oldPage;
	
	boolean isDown;
	boolean dataLoaded;
	public int touchPage;
	int firstPosition;

    public Pager(Context ctx, AttributeSet attrs) {
        super(ctx, attrs);
        con=ctx;
        contents = new LinearLayout(ctx);
        contents.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT));

        addView(contents);
        setVerticalScrollBarEnabled(false);
        setHorizontalScrollBarEnabled(false);
        
    }

    LinearLayout.LayoutParams measureParam=new LinearLayout.LayoutParams(0, LayoutParams.FILL_PARENT);
    @Override
    public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int specSize = MeasureSpec.getSize(widthMeasureSpec);
        measureParam.width=specSize;
        
        for (int i = 0; i < contents.getChildCount(); i++) {
            View child = contents.getChildAt(i);
            if (child.getLayoutParams().width != specSize) {
                child.setLayoutParams(measureParam);
            }
        }
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    @Override
    protected float getLeftFadingEdgeStrength() {
        return 0.0f;
    }

    @Override
    protected float getRightFadingEdgeStrength() {
        return 0.0f;
    }

    public void addPage(View child) {
        int width = getWidth();
        child.setLayoutParams(new LayoutParams(width, LayoutParams.FILL_PARENT));
        contents.addView(child);
        contents.requestLayout();
        
        firePageCountChanged();
    }
	@Override
	public boolean onInterceptTouchEvent(MotionEvent ev){

		if(ev.getPointerCount()==1&&ev.getAction()==MotionEvent.ACTION_DOWN){
			isDown=true;
			touchPage=getCurrentPage();
        	firstPosition=getScrollX();
		}
		if(ev.getPointerCount()==1&&ev.getAction()==MotionEvent.ACTION_MOVE)
			isDown=false;
		
		return super.onInterceptTouchEvent(ev); 
	}

    @Override
    public boolean onTouchEvent(MotionEvent evt) {
        boolean result = super.onTouchEvent(evt);
        
        int width = getWidth();

        if (evt.getAction() == MotionEvent.ACTION_UP) {
        	int distance=getScrollX()-firstPosition;
            int pg=touchPage ;
            if(distance<-20)
            	pg=touchPage-1;
            else if(distance>20)
            	pg=touchPage+1;
            smoothScrollTo(pg * width, 0);
            scrollTo(pg * width, 0);
            touchUpFinger();
        }

		if(evt.getPointerCount()==1&&evt.getAction()==MotionEvent.ACTION_DOWN){
			isDown=true;
			
			touchPage=getCurrentPage();
        	firstPosition=getScrollX();
		}
		if(evt.getPointerCount()==1&&evt.getAction()==MotionEvent.ACTION_MOVE)
			isDown=false;
        return result;
    }
    public void touchUpFinger(){
    }
    
	@Override
    public void onScrollChanged(int l, int t, int oldl, int oldt) {
        if (listeners != null) {
            for (OnPageChangeListener list: listeners) {
                list.onPageChange(this);
            }
        }
    }
	public boolean onInterceptHoverEvent(MotionEvent ev){
		return super.onInterceptTouchEvent(ev);
	}

    public boolean hasPage(View v) {
        return contents.indexOfChild(v) != -1;
    }

    public void removePage(View v) {
        contents.removeView(v);
        firePageCountChanged();

    }
    
    public int getCurrentPage() {
        int width = getWidth();
        return (getScrollX() + width/2) / width;
    }
    
    public void scrollToPage(int pg){
        int width = getWidth();

        smoothScrollTo(pg * width, 0);
        scrollTo(pg * width, 0);
        touchUpFinger();
    }

    public int getPageCount() {
        return contents.getChildCount();
    }

    public void removeAllPages() {
        contents.removeAllViews();
        firePageCountChanged();

    }

    private void firePageCountChanged() {
        if (listeners != null) {
            for (OnPageChangeListener list: listeners) {
                list.onPageCountChange(this);
            }
        }
    }


    
    public void addOnPageChangeListener(OnPageChangeListener onPageChangeListener) {
        if (listeners == null) {
            listeners = new LinkedList<OnPageChangeListener>();
        }
        listeners.add(onPageChangeListener);
    }
    
    public boolean removeOnPageChangeListener(OnPageChangeListener l) {
        if (listeners != null) {
            return listeners.remove(l);
        } else
            return false;
    }
    
    public void onShowView() {//may move to subscroll
    	if(!dataLoaded){
			LongOperation operate = new LongOperation(); 
			operate.execute("hello3");
			dataLoaded=true;
    	}
    }
    public void receiveData(){
    }
    protected class LongOperation extends AsyncTask<String, Void, String> {

		public LongOperation() {
			// TODO Auto-generated constructor stub
		}

		@Override
		protected String doInBackground(String... params) {
			publishProgress();
			try {
				HttpGet uri = new HttpGet(url);    

				DefaultHttpClient client = new DefaultHttpClient();
				HttpResponse resp = client.execute(uri);

				StatusLine status = resp.getStatusLine();
				if (status.getStatusCode()!=200) {
				    Log.d("hello", "HTTP error, invalid server status code: " + resp.getStatusLine());  
				}

				DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
				DocumentBuilder builder = factory.newDocumentBuilder();
				Document doc = builder.parse(resp.getEntity().getContent());
//				Log.v("hello",""+ doc.getChildNodes().getLength());
				list=doc.getChildNodes().item(0).getChildNodes();
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (ParserConfigurationException e) {
				e.printStackTrace();
			} catch (IllegalStateException e) {
				e.printStackTrace();
			} catch (SAXException e) {
				e.printStackTrace();
			}
			if(list==null){
				list=new NodeList() {
					
					@Override
					public Node item(int index) {
						// TODO Auto-generated method stub
						return null;
					}
					
					@Override
					public int getLength() {
						// TODO Auto-generated method stub
						return 0;
					}
				};
				
			}
			return "Executed";
		}

		@Override
		protected void onPostExecute(String result) {
			receiveData();
		}

		@Override
		protected void onPreExecute() {
		}

		@Override
		protected void onProgressUpdate(Void... values) {
		}
	}
}
